<?php
/**
 * Created by PhpStorm.
 * User: 10838
 * Time: 10:39
 */
namespace wechat;
use app\admin\model\MemberModel;
use think\Db;

class Wxtixian
{
    //支付密钥
    private $key='4c6749f18abaeea31dbe187f34eef2cE';
    public function index($openid,$amount)
    {
//        $openid = 'o_xYd1T5V8632-bCPh0Lcr92IzaM';
//        $openid = input('openid'); //用户的微信openid
//        $amount = input('amount'); //提现金额
        $num = is_numeric($amount);
        if (!$num)
        {
            return json(['code' => 0, 'data' => '', 'msg' => '提现金额必须为数字']);
        }
        else
        {
            if ($amount%100 == 0)
            {
               return $this -> PaytoUser($openid,$amount);
            }
            else
            {
                return json(['code' => 0, 'data' => '', 'msg' => '提现金额必须是100的整数倍']);
            }
        }
//        return view();
    }

    public function PaytoUser($openid,$amount)
    {
        $member = MemberModel::where('openid',$openid)->find();
        $array = func_get_args();
        $openid = $array[0];
        $amount = $array[1];
        $partner_trade_no = mt_rand(100,10000).time().mt_rand(0,1000); //生成订单编号
        if (empty($openid) && empty($amount) && empty($desc))
        {

        }
        else if (empty($openid))
        {
            return json(['code' => 0, 'data' => '', 'msg' => '请输入提现用户openid']);
        }
        else if (empty($amount))
        {
            return json(['code' => 0, 'data' => '', 'msg' => '请输入提现金额']);

        }
        else
        {
//            $url ="https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers";
            /***这个地方的商户号信息要换***/
            $par['mch_appid']	= 'wxd66ecbf25782cee9'; //申请商户号的appid或商户号绑定的appid
            /***微信支付的商户号需要替换***/
            $par['mchid']		= '1502238151'; //微信支付分配的商户号
            $par['nonce_str']   = $this->genRandomString(); //生成随机字符串
            $par['partner_trade_no'] = $partner_trade_no ;//商户订单号码必须唯一
            $par['openid']		= $openid; //客户的opendid
            $par['check_name']  = 'NO_CHECK';
            $par['amount']		= $amount * 100;
          //  $par['amount']		= ($amount * 100) * ((100-6)/100);//单位'分'

            $par['desc']		= '提现'.$member['mobile'];
            /***服务器的IP需要替换*192.168.0.1**/
//            $par['spbill_create_ip'] = '218.88.31.174' ;//用户端或者服务器的IP
            $par['spbill_create_ip'] = '47.106.164.73';
            $par['sign'] =$this->MakeSign($par);
            $return = $this -> ToXml($par);
            $url_isok = $this -> curl_post_ssl($return,'');
            $re = $this->xml_to_data($url_isok);
            if ($re['return_code'] == 'SUCCESS' and $re['result_code']== 'SUCCESS')
            {
//                return json(['code' => 0, 'data' => $re, 'msg' => '微信接口提交错误信息']);

                //提现成功
                //查询用户的

                $old = $member->money;

                $new_money = bcsub($old,$amount,2);
                $data = '原可用余额：'.$member->money.';现可用余额：'.$new_money.';提现:'.$amount.';手续费：6%'.';商户订单号:'.$re['partner_trade_no'].';微信订单号:'.$re['payment_no'].';微信支付成功时间:'.$re['payment_time'];
                money_log('用户提现',$data,$member->id,0,$member->money,$new_money,2,-$amount);
                Db::table('think_member')->where('openid',$openid)->update([
                    'money'=>$new_money
                ]);
//                echo "网路连接错误";
                return 200;
            }
            else
            {
//                echo $url_isok; //微信接口提交错误信息
                return $url_isok;
                return json(['code' => 0, 'data' => $url_isok, 'msg' => '微信接口提交错误信息']);

            }
        }

    }
    /**
     * 将xml转为array
     * @param string $xml
     * return array
     */
    public function xml_to_data($xml){
        if(!$xml){
            return false;
        }
        //将XML转为array
        //禁止引用外部xml实体
        libxml_disable_entity_loader(true);
        $data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $data;
    }
    /**
     * 产生一个指定长度的随机字符串,并返回给用户
     * @param type $len 产生字符串的长度
     * @return string 随机字符串
     */
    private function genRandomString($len = 32) {
        $chars = array(
            "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
            "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
            "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
            "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
            "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2",
            "3", "4", "5", "6", "7", "8", "9"
        );
        $charsLen = count($chars) - 1;
        // 将数组打乱
        shuffle($chars);
        $output = "";
        for ($i = 0; $i < $len; $i++) {
            $output .= $chars[mt_rand(0, $charsLen)];
        }
        return $output;
    }
    /**
     * 生成签名
     *  @return 签名
     */
    public function MakeSign( $params ){
        //签名步骤一：按字典序排序数组参数
        ksort($params);
        $string = $this->ToUrlParams($params);
        //签名步骤二：在string后加入KEY
//        $string = $string . "&key=".$this->key;
        $string = $string . "&key=4c6749f18abaeea31dbe187f34eef2cE";
        //签名步骤三：MD5加密

       $string = strtoupper(md5($string));
        //签名步骤四：所有字符转为大写
      //   $result = strtoupper($string);
//        return json(['code' => 0, 'data' => $string1, 'msg' =>$string ]);
       return $string;

    }
    /**
     * 将参数拼接为url: key=value&key=value
     * @param   $params
     * @return  string
     */
    public function ToUrlParams( $params ){
        $string = '';
        if( !empty($params) ){
            $array = array();
            foreach( $params as $key => $value ){
                $array[] = $key.'='.$value;
            }
            $string = implode("&",$array);
        }
        return $string;
    }
    /**
     * 转换数组成XML格式
     * [ToXml description]
     * @param [type] $arr [description]
     */
    public function ToXml($arr)
    {
        $xml = "<xml>";

        if (is_array($arr))
        {
            foreach ($arr as $key => $value)
            {
                if (is_numeric($value))
                {
                    $xml .= "<".$key.">".$value."</".$key.">";
                }
                else
                {
//                    $xml .= "<".$key.">"."<![CDATA[".$value."]]>"."</".$key.">";
                    $xml .= "<".$key.">".$value."</".$key.">";
                }
            }
            $xml .="</xml>";
            return $xml;
        }
        else
        {
//            echo "这里传入的必须是一个数组";
            return json(['code' => 0, 'data' => '', 'msg' => '这里传入的必须是一个数组']);

        }
    }
    /**
     * 提交到微信端口的控制函数
     * [curl_post_ssl description]
     * @param  [type] $value  [description]
     * @param  [type] $second [description]
     * @return [type]         [description]
     */
    public function curl_post_ssl($value,$second)
    {
        $url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers";
        if (empty($second))
        {
            $second = '30';
        }
        $ch = curl_init();
        /***设置超时设置***/
        curl_setopt($ch, CURLOPT_TIMEOUT, $second);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        /***设置传输设置***/
        curl_setopt($ch, CURLOPT_URL , $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER , false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST , false);
        curl_setopt($ch,CURLOPT_SSLKEYTYPE,'PEM');
//        curl_setopt($ch,CURLOPT_SSLKEY,getcwd().'/public/wxpay/apiclient_key.pem');
        curl_setopt($ch, CURLOPT_SSLCERT,getcwd().'/public/wxpay/apiclient_cert.pem');
        curl_setopt($ch, CURLOPT_SSLKEY,getcwd().'/public/wxpay/apiclient_key.pem');
        curl_setopt($ch, CURLOPT_CAINFO, getcwd().'/public/wxpay/rootca.pem'); // CA根证书（用来验证的网站证书是否是CA颁布）

       // curl_setopt($ch, CURLOPT_SSLKEY,"d:/Code/yunnan1/public/wxpay/apiclient_key.pem"); //特别注意：这里是服务器的绝对路径 且 绝对不能用变量代替！！！！！
        /***SDK要求是以POST方式上传***/
        curl_setopt($ch,CURLOPT_POST,1);
        curl_setopt($ch,CURLOPT_POSTFIELDS,$value);
        $data = curl_exec($ch);

        if ($data)
        {
            curl_close($ch);
            return $data;
            //print_r($data);
//            return $data;
            return json(['code' => 200, 'data' => $data, 'msg' => "发送成功"]);

        }
        else
        {
            $error = curl_errno($ch); //返回链接错误的信息


            curl_close($error);
            return $data;
            return json(['code' => 0, 'data' => $data, 'msg' => "call faild, errorCode:$error\n"]);
            return false;
        }
    }

    /**
     * PHP精确计算  主要用于货币的计算用
     * @param $n1 第一个数
     * @param $symbol 计算符号 + - * / %
     * @param $n2 第二个数
     * @param string $scale  精度 默认为小数点后两位
     * @return  string
     */
    function ncPriceCalculate($n1,$symbol,$n2,$scale = '2'){
        $res = "";
        switch ($symbol){
            case "+"://加法
                $res = bcadd($n1,$n2,$scale);break;
            case "-"://减法
                $res = bcsub($n1,$n2,$scale);break;
            case "*"://乘法
                $res = bcmul($n1,$n2,$scale);break;
            case "/"://除法
                $res = bcdiv($n1,$n2,$scale);break;
            case "%"://求余、取模
                $res = bcmod($n1,$n2,$scale);break;
            default:
                $res = "";break;
        }
        return $res;
    }
    /**
     * 价格由元转分
     * @param $price 金额
     * @return int
     */
    function ncPriceYuan2fen($price){
        $price = (int) ncPriceCalculate(100,"*", ncPriceFormat($price));
        return $price;
    }
    /**
     * 价格格式化
     *
     * @param int	$price
     * @return string	$price_format
     */
    function ncPriceFormat($price) {
        $price_format	= number_format($price,2,'.','');
        return $price_format;
    }


}

